{
 "cells": [
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "20b6d701",
   "metadata": {},
   "outputs": [],
   "source": [
    "import sys\n",
    "import os\n",
    "sys.path.append(os.path.abspath('..'))"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "afc843f7",
   "metadata": {},
   "source": [
    "# Modelo com Blocos Convolucionais\n",
    "CNN estruturada em blocos reutilizáveis."
   ]
  },
  {
   "cell_type": "markdown",
   "id": "ff9293eb",
   "metadata": {},
   "source": [
    "# Imports e Dataset"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "96aee263",
   "metadata": {
    "vscode": {
     "languageId": "plaintext"
    }
   },
   "outputs": [],
   "source": [
    "import torch\n",
    "import torchvision\n",
    "import torchvision.transforms as transforms\n",
    "from models.modelo_blocos import ModeloBlocos\n",
    "from utils.train import train\n",
    "from utils.test import test\n",
    "from utils.metrics import plot_confusion_matrix, plot_metrics\n",
    "\n",
    "device = torch.device(\"cuda\" if torch.cuda.is_available() else \"cpu\")\n",
    "\n",
    "transform = transforms.Compose([\n",
    "    transforms.ToTensor(),\n",
    "    transforms.Normalize((0.5,), (0.5,))\n",
    "])\n",
    "\n",
    "trainset = torchvision.datasets.CIFAR10(root='./data/dataset_usado', train=True, download=True, transform=transform)\n",
    "testset = torchvision.datasets.CIFAR10(root='./data/dataset_usado', train=False, download=True, transform=transform)\n",
    "\n",
    "trainloader = torch.utils.data.DataLoader(trainset, batch_size=64, shuffle=True)\n",
    "testloader = torch.utils.data.DataLoader(testset, batch_size=64, shuffle=False)\n",
    "\n",
    "classes = trainset.classes"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "c23fe387",
   "metadata": {},
   "source": [
    "# Treinamento com Blocos"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "5a7ec987",
   "metadata": {
    "vscode": {
     "languageId": "plaintext"
    }
   },
   "outputs": [],
   "source": [
    "model = ModeloBlocos(num_classes=10).to(device)\n",
    "criterion = torch.nn.CrossEntropyLoss()\n",
    "optimizer = torch.optim.Adam(model.parameters(), lr=0.001)\n",
    "\n",
    "train_losses, train_accuracies = [], []\n",
    "test_losses, test_accuracies = [], []\n",
    "\n",
    "for epoch in range(5):\n",
    "    train_loss, train_acc = train(model, trainloader, criterion, optimizer, device)\n",
    "    test_loss, test_acc = test(model, testloader, criterion, device)\n",
    "\n",
    "    train_losses.append(train_loss)\n",
    "    train_accuracies.append(train_acc)\n",
    "    test_losses.append(test_loss)\n",
    "    test_accuracies.append(test_acc)\n",
    "\n",
    "    print(f\"Epoch {epoch+1}: Train Acc={train_acc:.4f}, Test Acc={test_acc:.4f}\")"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "275bc390",
   "metadata": {},
   "source": [
    "# Matriz de Confusão"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "397de649",
   "metadata": {
    "vscode": {
     "languageId": "plaintext"
    }
   },
   "outputs": [],
   "source": [
    "y_true, y_pred = [], []\n",
    "model.eval()\n",
    "with torch.no_grad():\n",
    "    for images, labels in testloader:\n",
    "        images, labels = images.to(device), labels.to(device)\n",
    "        outputs = model(images)\n",
    "        _, preds = torch.max(outputs, 1)\n",
    "        y_true.extend(labels.cpu().numpy())\n",
    "        y_pred.extend(preds.cpu().numpy())\n",
    "\n",
    "plot_confusion_matrix(y_true, y_pred, classes)"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "5f5e68fb",
   "metadata": {},
   "source": [
    "# Gráficos"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "5a050262",
   "metadata": {
    "vscode": {
     "languageId": "plaintext"
    }
   },
   "outputs": [],
   "source": [
    "plot_metrics(train_accuracies, test_accuracies, train_losses, test_losses)"
   ]
  }
 ],
 "metadata": {
  "language_info": {
   "name": "python"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 5
}
